<template>
			<el-container>
				<el-aside width="50%" v-loading="menuloading">
					<el-container>
						<el-main class="nopadding" style="padding:20px;" ref="main">
			<h2>{{titleMap[mode]}}</h2>
		<el-form :model="form" :rules="rules" :disabled="mode=='show'" ref="dialogForm" label-width="100px">
			<el-form-item label="活动名称" prop="act_name">
				<el-input v-model="form.act_name" placeholder="请输入活动名称" clearable></el-input>
			</el-form-item>
			<el-form-item label="类型" prop="act_type">
				 <el-radio-group v-model="form.act_type">
				    <el-radio  v-for="(item, key) in act_types" :key="key" :label="key">{{item}}</el-radio>
				  </el-radio-group>
			</el-form-item>
			<el-form-item label="开始时间" prop="start_time">
				<el-date-picker style="width: 100%;" v-model="form.start_time" value-format="X" type="datetime"
				placeholder="活动开始时间" />
			</el-form-item>
			<el-form-item label="结束时间" prop="end_time">
				<el-date-picker style="width: 100%;" v-model="form.end_time" value-format="X" type="datetime"
				placeholder="活动结束时间" />
			</el-form-item>
			<!-- <el-form-item label="活动规则" prop="rules">
				<el-input v-model="form.rules" placeholder="请输入活动规则" type="textarea" clearable></el-input>
			</el-form-item> -->
			<el-form-item label="活动规则" prop="rules">
				<sc-editor v-model="form.rules" placeholder="请输入活动规则" :templates="templates" :height="400"></sc-editor>
			</el-form-item>
			<el-form-item label="活动封面" prop="cover">
				<sc-upload v-model="form.cover" title="上传活动封面"></sc-upload>
			</el-form-item>
			<el-form-item >
				<el-button @click="visible=false, close()">取 消</el-button>
				<el-button v-if="mode!='show'" type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
			</el-form-item>
		</el-form>
		</el-main>
		</el-container>
			</el-aside>
			<el-container>
				<el-main class="nopadding" style="padding:20px;" ref="main">
							<h2>活动奖品</h2>
							<sc-form-table v-model="form.detail" :addTemplate="apiListAddTemplate" placeholder="暂无活动奖品">
								<el-table-column prop="num" label="数量">
									<template #default="scope">
										<el-input-number v-model="scope.row.num" controls-position="right" :precision="0" :min="1"
											style="width: 100%;"></el-input-number>
									</template>
								</el-table-column>
								<el-table-column prop="rate" label="概率">
									<template #default="scope">
										<div class="rate" style="display: flex;align-items: center;">
											<!-- <el-input-number @change="rateChange(scope.$index, $event)" v-model="scope.row.rate" :precision="2" :min="0" :max="99"
											style="width: 100%;margin-right: 5px;"></el-input-number> -->
											<el-input-number v-model="scope.row.rate" :precision="2" :min="0" :max="100"
											style="width: 100%;margin-right: 5px;"></el-input-number>
										%</div>
									</template>
								</el-table-column>
								<el-table-column prop="cover" label="图片" width="170px">
									<template #default="scope">
										<sc-upload v-model="scope.row.cover" title="上传产品图"></sc-upload>
									</template>
								</el-table-column>
								<el-table-column prop="limit" label="限制中奖次数">
									<template #default="scope">
										<el-input-number v-model="scope.row.limit" controls-position="right" :precision="0" :min="1"
											style="width: 100%;"></el-input-number>
									</template>
								</el-table-column>
							</sc-form-table>
				</el-main>
			</el-container>
		</el-container>
</template>

<script>
	import useTabs from "@/utils/useTabs"
	import { defineAsyncComponent } from 'vue';
	const scEditor = defineAsyncComponent(() => import('@/components/scEditor'));
	export default {
		components: {
			scEditor
		},
		data() {
			return {
				mode: "add",
				titleMap: {
					add: '新增活动',
					edit: '编辑活动',
					show: '查看'
				},
				visible: false,
				isSaveing: false,
				//表单数据
				form: {
					id: "",
					act_name: "",
					act_type: '1',
					start_time: '',
					end_time: '',
					rules: '',
					cover: '',
					detail: []
				},
				act_types: {'1': '大转盘'
				// , '2': '砸金蛋', '3': '刮刮乐',
				},
				//验证规则
				rules: {
					act_name: [{
						required: true,
						message: '请输入活动名称'
					}],
					start_time: [{
						required: true,
						message: '请选择活动开始时间'
					}],
					end_time: [{
						required: true,
						message: '请选择活动结束时间'
					}],
					rules: [{
						required: true,
						message: '请输入活动规则'
					}],
					cover: [{
						required: true,
						message: '请上传活动封面图'
					}],
					// detail: [{
					// 	required: true,
					// 	message: '请添加活动奖品'
					// },{
					//   validator: (rule, value, callback) => {
					// 	// 判断 value 和 当前 form 中收集的 password 是否一致
					// 	if (value.length == 0) {
					// 	  callback(new Error('请添加活动奖品'))
					// 	} else {
					// 	  callback() // 校验成功
					// 	}
					//   },
					// }],
					// remark: [{
					// 	required: true,
					// 	message: '请输入备注'
					// }]
				},
				// apiListAddTemplate: {
				// 	id: this.apiListAddTemplateId,
				// 	num: "10",
				// 	rate: "3",
				// 	cover: "",
				// 	limit: "1"
				// },
				templates: [
					{
						title: '自定义HTML模板',
						description: '',
						content: '<strong>演示模板</strong>'
					},
					{
						title: '列表',
						description: '',
						content: '<ol><li>演示列表1</li><li>演示列表2</li></ol>'
					}
				],
				apiListAddTemplate: {
					num: "10",
					rate: "3",
					cover: "",
					limit: "1"
				}
			}
		},
		mounted() {
			if (this.$route.params.id && this.$route.params.id != '0') {this.form.id = this.$route.params.id;this.getDetail();this.mode = 'edit';useTabs.setTitle(this.titleMap[this.mode])}
			else useTabs.setTitle(this.titleMap[this.mode])
		},
		computed: {
			// apiListAddTemplate () {
			// 	return {
			// 		id: this.form.detail.length+1,
			// 		num: "10",
			// 		rate: "3",
			// 		cover: "",
			// 		limit: "1"
			// 	}
			// }
		},
		methods: {
			//显示
			// open(mode = 'add') {
			// 	this.mode = mode;
			// 	this.visible = true;
			// 	if (mode== 'add') {
			// 		this.form = {
			// 			id: "",
			// 			act_name: "",
			// 			act_type: '1',
			// 			start_time: '',
			// 			end_time: '',
			// 			rules: '',
			// 			cover: '',
			// 			detail: []
			// 		}
			// 	}
			// 	return this
			// },
			close() {
				useTabs.close()
			},
			timeChange(value) {
				this.form.start_time = value[0]
				this.form.end_time = value[1]
			},
			//表单提交方法
			async submit() {
				var valid = await this.$refs.dialogForm.validate().catch(() => {})
				if (!valid) {
					return false
				}
				if (this.form.detail.length == 0) {
					this.$message.error("请添加活动奖品")
					return false
				}
				let detailMax = this.form.detail.reduce((sum, item) => sum + item.rate, 0)
				if (detailMax != 100) {
					this.$message.error("活动奖品概率必须等于100")
					return false
				}
				this.isSaveing = true;
				let form = JSON.parse(JSON.stringify(this.form))
				form.start_time = parseInt(form.start_time)
				form.end_time = parseInt(form.end_time)
				form.detail = JSON.stringify(form.detail)
				var res;
				if (this.form.id) {
					res = await this.$API.marketing.activity.update.post(form);
				} else {
					res = await this.$API.marketing.activity.create.post(form);
				}

				this.isSaveing = false;
				if (res.code == 200) {
					if (this.mode == 'add') {
						this.form.id = res.data
					}
					let form = JSON.parse(JSON.stringify(this.form))
					this.$emit('success', form, this.mode)
					this.visible = false;
					this.$message.success("操作成功")
					setTimeout(() => {
						// this.$router.go(-1);
						// useTabs.close()
							this.$router.replace({
								path: '/marketing/Activity'
							})
					}, 800)
					// this.$alert("密码修改成功，是否跳转至登录页使用新密码登录", "修改成功", {
					// 	type: 'success',
					// 	center: true
					// }).then(() => {
					// 	this.$router.replace({
					// 		path: '/login'
					// 	})
					// }).catch(() => {})
				} else {
					this.$alert(res.message || res.msg, "提示", {
						type: 'error'
					})
				}
			},
			async getDetail() {
				let res = await this.$API.marketing.activity.detail.get({id: this.form.id});

				if (res.code == 200) {
					this.setData(res.data)
					// this.$alert("密码修改成功，是否跳转至登录页使用新密码登录", "修改成功", {
					// 	type: 'success',
					// 	center: true
					// }).then(() => {
					// 	this.$router.replace({
					// 		path: '/login'
					// 	})
					// }).catch(() => {})
				} else {
					this.$alert(res.message || res.msg, "提示", {
						type: 'error'
					})
				}
			},
			//表单注入数据
			setData(data) {
				this.form.id = data.id
				this.form.act_name = data.act_name
				this.form.act_type = data.act_type.toString()
				this.form.start_time = data.start_time
				this.form.end_time = data.end_time
				this.form.rules = data.rules
				this.form.cover = data.cover
				if (data.detail) {
					if (typeof data.detail === 'string') this.form.detail = JSON.parse(data.detail)
					else this.form.detail = data.detail
				}
				//可以和上面一样单个注入，也可以像下面一样直接合并进去
				//Object.assign(this.form, data)
			},
			rateChange(index, e) {
				let sun =this.form.detail.reduce((accumulator, current) => accumulator + current.rate, 0)
				if (sun > 100) {
					let sun0 = sun - e
					let obj = this.form.detail[index]
					obj.rate = 100 - sun0
				}
			}
		}
	}
</script>

<style scoped>
	h2 {font-size: 17px;color: #3c4a54;padding:0 0 30px 0;}
	.apilist {border-left: 1px solid #eee;}

	[data-theme="dark"] h2 {color: #fff;}
	[data-theme="dark"] .apilist {border-color: #434343;}

	/* 隐藏加号按钮 */
	/* .rate ::v-deep .el-input-number__increase {
	  display: none;
	} */

	/* 隐藏减号按钮 */
	/* .rate ::v-deep .el-input-number__decrease {
	  display: none;
	} */
</style>
